/* ******************************************************************
 * This file is part of the escal project and distributed under the
 * terms of the GNU General Public License Version 3
 * Copyright (C) 2008 Epocher (xijiaosdq@gmail.com)
 * See COPYING file for licensing information.
 *******************************************************************/

#include "escal.h"
#include "preference_dialog.h"
#include "utils/general_config.h"
#include "utils/network_config.h"
#include <QListWidgetItem>
#include <QMessageBox>

PreferenceDialog::PreferenceDialog(QWidget *parent)
	:QDialog(parent)
{
	setupUi(this);
	addWidgets();

	
	formerRow=0;
	listWidget->setCurrentRow(formerRow);
	widgetList[0]->show();
	connect(listWidget, SIGNAL(activated ( const QModelIndex)),
			this, SLOT(changeRow(const QModelIndex&)));
}

void PreferenceDialog::addWidgets(){
	QLayout *layout = new QGridLayout(contentWidget);
	contentWidget->setLayout(layout);

	BaseConfigWindow *widget;
	QListWidgetItem *item;

	widget = new GeneralConfig(this);
	widgetList << widget;
	layout->addWidget(widget);
	widget->hide();
	item = new QListWidgetItem(
			widget->windowIcon(),
			widget->windowTitle(),
			listWidget);
	listWidget->addItem(item);

	widget = new NetworkConfig(this);
	widgetList << widget;
	layout->addWidget(widget);
	widget->hide();
	item = new QListWidgetItem(
			widget->windowIcon(),
			widget->windowTitle(),
			listWidget);
	listWidget->addItem(item);
}

void PreferenceDialog::changeRow(
		const QModelIndex& current){
	int currentRow = current.row();
	int result;
	if(formerRow!=currentRow){
		if(widgetList[formerRow]->isModified()){
			result = QMessageBox::question(this, 
					tr("settings have been modified"),
					tr("settings have been modified\n"
					"do you want to apply it?"),
					QMessageBox::Apply|QMessageBox::Discard|
					QMessageBox::Cancel,
					QMessageBox::Apply);
			if(result == QMessageBox::Cancel){
				qDebug() << "QMessageBox::Cancel";
				listWidget->setCurrentRow(formerRow);
				return;
			}
			else if(result == QMessageBox::Apply){
				widgetList[formerRow]->apply();
			}
		}
		widgetList[formerRow]->hide();
		formerRow=currentRow;
		widgetList[formerRow]->show();
	}
}

void PreferenceDialog::accept(){
	widgetList[formerRow]->apply();
	QDialog::accept();
};

void PreferenceDialog::reject(){
	widgetList[formerRow]->reset();
	QDialog::reject();
};

void PreferenceDialog::applyCurrent(){
	widgetList[formerRow]->apply();
};

void PreferenceDialog::resetCurrent(){
	widgetList[formerRow]->reset();
};

void PreferenceDialog::setDefaultCurrent(){
	widgetList[formerRow]->setDefaults();
};

